--
-- Author:      name
-- DateTime:    2018-08-21 15:57:48
-- Description: 游戏主逻辑

local skynet = require "skynet"
local log = require "Log"
local config = require "configquery"
local Timer = require "timer"
local FSM = require "fsm"
local NodeMessage = require "NodeMessage"
local Universal = require "Universal"
local json = require "cjson"
require "common"


local mix_array = mix_array
local table_clone = table_clone
local floor = math.floor
local four_five = math.four_five
local random = math.random



local MachineBase = require "common.MachineBase"
local Machine = class("Machine",MachineBase)

function Machine:ctor(tableid,rule)
	json.encode_sparse_array(true)
	self.super:ctor(tableid,rule) --父类

	--状态时间
	self.stateTime = {	
		rest = 5,		--休息时间
		start = 15,		--开始(下注)
		card = 16,	    --选择比牌操作时间		
		settlement = 5, --结算时间
	}
	
	--加注列表
	self.chipList = {1000, 10000, 100000, 1000000, 10000000}
	--配置信息
	self.maxRound = 6 --最大轮数
	self.playerNum = 0 --参与下注的人数
	self.allBetChip = 0 --所有玩家总共下注

	--位置id 1中， 2发， 3白
	self.poolName = {zhong = 1, fa = 2, bai = 3}
	self.maxPoolid = 3
	self.poolAllBet = {} --已下注总分
	self.poolPlayerAllBet = {} --各个池所有玩家的下注总分
	self.poolPlayerChipList = {} --各个池所有玩家的下注筹码列表
	self.poolChipList = {} --筹码列表
	self.prePoolPlayerChipList = {} --上次下注
	self.winList = {} --赢的池id记录
	self.curRound = 0
	self.curCards = {} --
	self.zhuangSeatid = 9	--庄家座位id	
	self.sysZhuangChip = 1000000000
	self.sysZhuangHeadIcon = "http://cnd.7cpoker.com/image/header/hearder1.png"
	self.seatMinMoney = 1000000--000	--最低坐下钱
	self.seatZhuangMinMoney = 1000000--00000	--最低坐庄钱
	self.sysZhuangNick = "钱多多"
	self.zhuangPalyerList = {} --待上庄队列	
	self.zhuangLeftChip = 0 --当前上庄玩家剩余钱
	--开始时系统坐庄
	self.zhuangLeftChip = self.sysZhuangChip
	self.isSysZhuang = true -- 是否系统庄	
	self.sysZhuangPlayerId = 0 --系统庄id
	self.sysDefaultGame = 2 --php统计用
	self.zhuangPlayerId = self.sysZhuangPlayerId --上庄玩家id
	self.canBetMinMonney = 20000	 --最低下注不得低于这多
	
	self.profitWantXiazhuang = false -- 盈利了想要下庄
	self.severFeeRate = 0.05	--服务费率
	self.winLossHistoryList = {} --输赢记录
	self.maxHistoryCount = 13 --输赢记录
	self.trdid = 0	--当前牌桌玩了几局

	self.tbPlayerWinChip = {} --各玩家所赢的金币
	self.winPoolid = {} --赢的池id
	self.tbPlayerAllBet = {} --玩家总下注
	self.tbTableStateValue = {	
						start = 1,
						card = 2,
						settlement = 3,
						rest = 4,
					}
	--状态
	--休息，开始玩家操作，发牌，结算
	--state1 --eventName --state2 --callback
	self.gameStateTransitionTable = {
		{"rest", 		"to_start", 			"start", 			function() self:onStart() end },
		{"start", 		"to_card",				"card", 			function() self:onCard() end },
		{"card", 	    "to_settlement",		"settlement", 		function() self:onSettlement() end },
		{"settlement", 	"to_rest", 				"rest", 			function() self:onRest() end },
	}
	--状态机
	self.fsm = FSM.new(self.gameStateTransitionTable)
	self:reset()
end

--override加入玩家
function Machine:addPlayer(player)
	player.zhuangChipFreeze = 0
	self.super.addPlayer(self, player)
end
---------------------------------------------------------
-- private
---------------------------------------------------------
--重置数据
function Machine:reset()
	if self.rule:getLeftCardCount() <= 0 then
		self.rule:shuffle()
		self.curRound = 0
	end
		
	self.playerNum = 0
	self.prePoolPlayerChipList = self:mergePoolChip(self.poolPlayerChipList)

	self.tbBeforeStart = {}
	self.poolAllBet = {} --已下注总分
	self.poolPlayerChipList = {}	
	for i=1,self.maxPoolid do 
		self.poolAllBet[i] = 0
		self.poolPlayerAllBet[i] = {}
		self.poolPlayerChipList[i] = {}
		self.poolChipList[i] = {}
	end

	self.operStartTime = 0
	self.winPoolid = {} --赢的池id
	self.tbPlayerWinChip = {} --各玩家所赢的金币
end

--更新大厅中传来的玩家数据
function Machine:updateProperty(playerid, data)
	local player = self.player_list[playerid]
	if not player then 
		return 
	end
	for k,v in pairs(data) do 
		player[k] = v
	end
	local seatPlayer = self:getSeatPlayer(player)      
	local data = {zfb_nt_player_info_change = seatPlayer}
	self:sendToAll(data)
end

function Machine:getSeatPlayer(player)
	local seatPlayer = self.super:getSeatPlayer(player)
	if self.zhuangPlayerId == seatPlayer.playerid then
    	seatPlayer.seatid = self.zhuangSeatid
    end
	return seatPlayer
end

--桌子人数
function Machine:getNoSeatPlayerNum()
	local num = 0
	for k,v in pairs(self.player_list) do
		if not v.seatid and self.zhuangPlayerId ~= v.playerid then
			num = num + 1 	
		end
	end
	return num
end

--离线清除
function Machine:removeDisconnect()
	for k,v in pairs(self.player_list) do 
		if v.disconnect 
			and self:getBetByPlayerId(playerid) <= 0
			and v.playerid ~= self.zhuangPlayerId then 	
			local sql = string.format("delete from user_online where uid = %d;", v.playerid)
			  skynet.send("mysql_service", "lua", "execute", sql)
			self:sitUp(k)
			self.player_list[k] = nil
			self:updatePlayerNum()
			--清除玩家所在桌子id
			self:sendGate(v, 'update_tableid', 0)	
			print("踢走离线#######",k)		
		end
	end
end

--离开桌子
function Machine:leaveTable(playerid)
	if playerid == self.zhuangPlayerId then
		AssertEx(false, 'leave_table_res', 39)
	end
	if self:getBetByPlayerId(playerid) > 0 then
		AssertEx(false, 'leave_table_res', 40)
	end
	log.debug('玩家离开牌桌>>>>>>>>>>>',playerid,self.tableid)
	local player = self.player_list[playerid]
	for k, v in pairs(self.zhuangPalyerList) do
		if v == playerid then
			table.remove(self.zhuangPalyerList, k)
			local reason = {
				code = 6,
				moneytype = 1,
				game = player.game,
				gameid = self.gameid,
				gametype = self.roomid,
			}
			local money = self:callGate(player, 'change_money', player.zhuangChipFreeze, reason)
			break
		end
	end
	local res = self:sitUp(playerid)
	self.player_list[playerid] = nil	
	self:updatePlayerNum()
	skynet.sleep(2)	
	return res
end

--掉线处理
function Machine:disconnect(playerid)	
	local player = self.player_list[playerid]
	log.debug('玩家掉线>>>>>>>>>>>',playerid,self.tableid,player.playing,player.disconnect)
	--旁观者掉线马上踢出大厅
	if not player.playing and player.disconnect
		 and self:getBetByPlayerId(playerid) <= 0 --在下注
		 and player.playerid ~= self.zhuangPlayerId then -- 在结算
		for k, v in pairs(self.zhuangPalyerList) do
			if v == playerid then
				table.remove(self.zhuangPalyerList, k)
				local reason = {
					code = 6,
					moneytype = 1,
					game = player.game,
					gameid = self.gameid,
					gametype = self.roomid,
				}
				local money = self:callGate(player, 'change_money', player.zhuangChipFreeze, reason)
				break
			end
		end
		print("########在旁观玩家中直接踢走")	
		self:sendGate(player, 'update_tableid', 0)
		self:sitUp(playerid)
		self.player_list[playerid] = nil
		return true
	end	
	return false
end

function Machine:getAllBet()
	local bet = 0
	for k,v in pairs(self.poolAllBet) do
		bet = bet + v
	end 
	return bet
end

function Machine:getBetByPlayerId(playerid)
	local bet = 0
	for poolid = 1, self.maxPoolid do
		if self.poolPlayerAllBet[poolid][playerid] then
			bet = bet + self.poolPlayerAllBet[poolid][playerid]
		end
	end
	return bet
end

function Machine:getPlayerInfo(playerid)
	local player = self.player_list[playerid]
	local playerInfo = {}
	if table.empty(player) then
		return {}
	end
	playerInfo.seatid = player.seatid 
	playerInfo.playerid = player.playerid 
	playerInfo.nick = player.nick 
	playerInfo.chip = player.chip 
	playerInfo.icon = player.icon 
	playerInfo.diamond = player.diamond 
	playerInfo.viplevel = player.viplevel 
	playerInfo.level = player.level
	playerInfo.freeze_chip = player.zhuangChipFreeze 
	return playerInfo
end

--下庄结算
function Machine:settleXiaZhuang()
	if not self.isSysZhuang then	
		local player = self.player_list[self.zhuangPlayerId]
		local reason = {
			code = 6,
			moneytype = 1,
			game = player.game,
			gameid = self.gameid,
			gametype = self.roomid,
		}
		local money = self:callGate(player, 'change_money', self.zhuangLeftChip, reason)
		if money then
			player.chip = money
		end
		
		if self.curRound == 0 then
			local str = ""
			local data = {}
			if self.zhuangLeftChip > player.zhuangChipFreeze then
				str = string.format("%s 在上轮坐庄中 赢了%d金币, 恭喜他！", player.nick, math.abs(self.zhuangLeftChip - player.zhuangChipFreeze))
				data = { nt_content_prompt = {type = 1, strContent = str} }
				self:sendToAll(data)
			elseif self.zhuangLeftChip < player.zhuangChipFreeze then
				str = string.format("%s 在上轮坐庄中 输了%d金币, 感谢他的付出！", player.nick, math.abs(self.zhuangLeftChip - player.zhuangChipFreeze))
				data = { nt_content_prompt = {type = 1, strContent = str} }
				self:sendToAll(data)
			else
				--不赢不输不提示
			end			
		elseif self.zhuangLeftChip < 0.2 * player.zhuangChipFreeze then
			local str = string.format("%s 因金额不足上庄金额的20%%，被迫下庄了，请再接再厉！", player.nick)
			data =  { nt_content_prompt = {type = 1, strContent = str} }
			self:sendToAll(data)
		end			
	
		player.zhuangChipFreeze = 0
		local seatPlayer = self:getSeatPlayer(player)
		seatPlayer.seatid = nil
		self:updateProperty(playerid, seatPlayer)
	end
end	
	
--换庄
function Machine:changeZhuang()
	if self.zhuangPlayerId == 0 and #self.zhuangPalyerList <= 0 then
		return --当前系统庄且上庄队列无人
	end
	--当前系统庄且上庄队列有人，
	--或当前非系统庄队列无人，
	--或当前非系统庄队列有人
	if self.profitWantXiazhuang or 
	    (self.isSysZhuang and #self.zhuangPalyerList > 0) or
	    (not self.isSysZhuang and self.curRound == 0) or
	    (not self.isSysZhuang and self.zhuangLeftChip < 0.2 * self.player_list[self.zhuangPlayerId].zhuangChipFreeze) then		
		local function _getPlayer(playerid)
			local playerInfo = {}
			if playerid == 0 then -- 系统
				playerInfo.icon = self.sysZhuangHeadIcon
				playerInfo.playerid = 0
				playerInfo.nick = self.sysZhuangNick
			else
				local player= self.player_list[playerid]
				playerInfo.icon = player.icon
				playerInfo.playerid = player.playerid
				playerInfo.nick = player.nick			
			end
			playerInfo.seatid = self.zhuangSeatid			
			return playerInfo
	    end

	    --旧庄坐站起	    	    
	    local seatPlayer = _getPlayer(self.zhuangPlayerId)
	    local data = {zfb_nt_seat_change = {
			tableid = self.tableid,
			seat_player = seatPlayer,
			seat = false,
		}}
		self:sendToAll(data)
		self:settleXiaZhuang()

		self.curRound = 0
		self.rule:shuffle()
		self.profitWantXiazhuang = false
		log.debug("------------------------------------旧坐庄玩家先站起", seatPlayer)

		if #self.zhuangPalyerList > 0 then
			self.zhuangPlayerId = table.remove(self.zhuangPalyerList, 1)
		else
			self.zhuangPlayerId = 0
		end
		self.isSysZhuang = (self.zhuangPlayerId == self.sysZhuangPlayerId)		

		if self.isSysZhuang then
			self.zhuangLeftChip = self.sysZhuangChip
		else
			self.zhuangLeftChip = self:getPlayer(self.zhuangPlayerId).zhuangChipFreeze
		end
	  
		--新上庄如果在座位上先站起
		local newzhangPlayer = self.player_list[self.zhuangPlayerId]
		if newzhangPlayer and newzhangPlayer.seatid then
			self.seat_list[newzhangPlayer.seatid] = nil				
			local seatPlayer = _getPlayer(self.zhuangPlayerId)
			seatPlayer.seatid = newzhangPlayer.seatid
			newzhangPlayer.seatid = nil	
		    local data = {zfb_nt_seat_change = {
				tableid = self.tableid,
				seat_player = seatPlayer,
				seat = false,
			}}
			log.debug("------------------------------------玩家坐庄先站起", newzhangPlayer)
			self:sendToAll(data)
		end

		--新庄坐下
		local seatPlayer = _getPlayer(self.zhuangPlayerId)
		seatPlayer.chip = self.zhuangLeftChip
	    local data = {zfb_nt_seat_change = {
			tableid = self.tableid,
			seat_player = seatPlayer,
			seat = true,
		}}
		log.debug("------------------------------------玩家坐庄", seatPlayer)
		self:sendToAll(data)
		self:ntNoSeatPlayerNum()
	end
end
---------------------------------------------------------
-- 状态
---------------------------------------------------------

--休息
function Machine:onRest()
	log.debug("_______onRest")
	self.operStartTime = os.time()

	--重置数据
	self:reset()
	self:ntXiazhuangPrompt()
	self:ntRest()
	self:removeDisconnect()

	for k,v in pairs(self.player_list) do
		if v.chip < self.seatMinMoney and v.seatid then
			self:sitUp(v.playerid)
		end
	end

	local callback = function ( ... )
		self.fsm:fire("to_start")		
	end
	self:setTime(self.stateTime.rest, callback)
end


--开始
function Machine:onStart()
	log.debug("_______onStart")	
	self.trdid = self.trdid + 1
	self:loadStockConfig()
	self:changeZhuang()
	self.operStartTime = os.time()
	self.curRound = self.curRound + 1
	if self.isSysZhuang then
		if self.zhuangLeftChip < 1000000 or self.zhuangLeftChip > 2000000000 then
			print()
			self.zhuangLeftChip = self.sysZhuangChip
		end
	end
	--开始下注
	local callback = function ()
		--停止下注
		self.fsm:fire("to_card")
	end
	self:setTime(self.stateTime.start, callback)
	self:ntStart()
	-- self:ntCardToRoot()
end

--发牌
function Machine:onCard()
	log.debug("_______onCard")	
	self.operStartTime = os.time()	
	local callback = function ()
		self.fsm:fire("to_settlement")
	end
	self:setTime(self.stateTime.card,callback)
	for k,v in pairs(self.player_list) do 
		self.tbBeforeStart[k] = v.chip
	end

	--取牌
	self.curCards = self.rule:getCards()
	self.calGetCardTime = os.time()
	self.count = 0
	self.curCards = self:getCardWithStock(table.copy(self.curCards)) or self.curCards
	self.zhongCard  = {self.curCards[1], self.curCards[2]}
	self.faCard		= {self.curCards[3], self.curCards[4]}
	self.baiCard 	= {self.curCards[5], self.curCards[6]}
	self.zhuangCard = {self.curCards[7], self.curCards[8]}

	local tbDice = {math.random(1, 6), math.random(1, 6)}
		
	local data = {
		zfb_nt_card = {
			tableid = self.tableid,
			time = self.stateTime.card,
			cards = self.curCards,
			diceArr = tbDice,	

		}
	}
	self:sendToAll(data)
end

--每种筹码的个数
function  Machine:getBetChipTypeNum(chipsList, tbChips)
	local tb = {}
	for k, v in pairs(chipsList) do
		tb[k] = 0
		for i, u in pairs(tbChips) do
			if v == u then
				tb[k] = tb[k] + 1
			end
		end
	end
	return tb
end

--结算
function Machine:onSettlement()
	log.debug("_______onSettlement")
	self.operStartTime = os.time()	
		
	--玩家
	local tbPlayerWinChip = {}
	local zhuangWinChip = 0
	for k, v in pairs(self.player_list) do
		playerWinChip = 0
		for poolid = 1, self.maxPoolid do	 
			local betChips = self.poolPlayerAllBet[poolid][v.playerid]
			if betChips and betChips > 0 then
				local resCompare
				if poolid == self.poolName.zhong then
					resCompare =self.rule:compareCard(self.zhuangCard, self.zhongCard) 
				elseif poolid == self.poolName.fa then
					resCompare =self.rule:compareCard(self.zhuangCard, self.faCard) 
				elseif poolid == self.poolName.bai then
					resCompare =self.rule:compareCard(self.zhuangCard, self.baiCard) 
				end

				if resCompare > 0 then  --庄家赢
					zhuangWinChip = zhuangWinChip + betChips
				else--玩家赢
					playerWinChip = playerWinChip + betChips * 2
					zhuangWinChip = zhuangWinChip - betChips
				end
			end
		end
		playerWinChip = playerWinChip - self:getBetByPlayerId(v.playerid)
		local serviceFree = 0
		if playerWinChip > 0 then
			serviceFree = math.floor(playerWinChip * self.severFeeRate)
			playerWinChip =  playerWinChip - serviceFree
		end
		tbPlayerWinChip[v.playerid] = playerWinChip
		if playerWinChip + self:getBetByPlayerId(v.playerid) > 0 then
			local reason = {
				code = 2,
				moneytype = 1,
				game = v.game,
				gameid = self.gameid,
				gametype = self.roomid,
			}
			local money = self:callGate(v, 'change_money', playerWinChip + self:getBetByPlayerId(v.playerid), reason)
			if money then
				v.chip = money
			end
			local tableName = 'service_charge_log'.. os.date("%Y%m%d")
			local str = tableName .." (uid, charge, banker, sid, time, game, gameid, gametype)"
			local sql = string.format("insert into %s values(%d,%d,%d,%d,%d,%d,%d,%d);",
				str, v.playerid, serviceFree, 2, v.seatid or 0, os.time(), v.game or 0, self.gameid, self.roomid)
			local r = skynet.send("mysql_log", "lua", "execute", sql)
		end
	end

	if zhuangWinChip > 0 then
		--庄家输赢的钱在下庄时才存数据库
		local serviceFree = math.floor(zhuangWinChip * self.severFeeRate)
		local game = self.sysDefaultGame
		if self.zhuangPlayerId > 0 then
			game = self.player_list[self.zhuangPlayerId].game
		end		
		zhuangWinChip = zhuangWinChip - serviceFree
		local tableName = 'service_charge_log'.. os.date("%Y%m%d")
		local str = tableName .." (uid, charge, banker, sid, time, game, gameid, gametype)"
		local sql = string.format("insert into %s values(%d,%d,%d,%d,%d,%d,%d,%d);",
			str, self.zhuangPlayerId, serviceFree, 1, self.zhuangSeatid, os.time(), game, self.gameid, self.roomid)
		local r = skynet.send("mysql_log", "lua", "execute", sql)
	end

	print("zhuangLeftChip", self.zhuangLeftChip, zhuangWinChip)
	self.zhuangLeftChip = self.zhuangLeftChip + zhuangWinChip

	local zhuangSettle = {}
	zhuangSettle.seatid = self.zhuangSeatid
	zhuangSettle.winChips = zhuangWinChip
	zhuangSettle.chip = self.zhuangLeftChip

	local tbZhaungWinlose = {}
	local resCompare
	for poolid = 1, self.maxPoolid do
		if poolid == self.poolName.zhong then
			resCompare =self.rule:compareCard(self.zhuangCard, self.zhongCard) 
		elseif poolid == self.poolName.fa then
			resCompare =self.rule:compareCard(self.zhuangCard, self.faCard) 
		elseif poolid == self.poolName.bai then
			resCompare =self.rule:compareCard(self.zhuangCard, self.baiCard) 
		end
		tbZhaungWinlose[poolid] = (resCompare > 0)
	end
	if #self.winLossHistoryList >= self.maxHistoryCount then
		table.remove(self.winLossHistoryList, 1)
	end
	table.insert(self.winLossHistoryList, {pool_win = tbZhaungWinlose})
	
	--座位玩家
	local seatPlayers = self:getSeatPlayers()
	local tbSeatSettle = {}
	for k, v in pairs(seatPlayers) do
		seatSettle = {}
		local poolChips = {}
		for poolid = 1, self.maxPoolid do	
			local tbChips = self.poolPlayerChipList[poolid][v.playerid]	or {}
			local tbChipTypeNum = self:getBetChipTypeNum(self.chipList, tbChips)	
			table.insert(poolChips, {poolid = poolid, chip_Type_Num_list = tbChipTypeNum})
		end		
		seatSettle.seatid = v.seatid
		seatSettle.playerid = v.playerid
		seatSettle.pool_chips = poolChips
		seatSettle.winChips = tbPlayerWinChip[v.playerid]
		seatSettle.chip = v.chip
		table.insert(tbSeatSettle, seatSettle) 
	end

	for k, v in pairs(self.player_list) do	
		local myselfSettle = {}
		myselfSettle.winChips = tbPlayerWinChip[v.playerid]
		myselfSettle.chip = v.chip
		myselfSettle.seatid = v.seatid
		myselfSettle.playerid = v.playerid
		local poolChips = {}
		for poolid = 1, self.maxPoolid do	
			local tbChips = self.poolPlayerChipList[poolid][v.playerid]	or {}
			local tbChipTypeNum = self:getBetChipTypeNum(self.chipList, tbChips)	
			table.insert(poolChips, {poolid = poolid, chip_Type_Num_list = tbChipTypeNum})		
		end
		myselfSettle.pool_chips = poolChips

		local data = {zfb_nt_end={
	 		table_id = self.tableid,	
	 		seat_settle = tbSeatSettle,
	 		zhuang_settle = zhuangSettle,
	 		cur_round = self.curRound,		
	 		myself_settle = myselfSettle,
	 		winlose = tbZhaungWinlose,
		}}
		--print("__________zfb_nt_end:", data)

		self:sendMessage(k, data)
	end
	
	print("__________zfb_nt_end")
	local callback = function ()
		--休息
		self.fsm:fire("to_rest")
	end
	self:setTime(self.stateTime.settlement, callback)

	self:record({tbPlayerWinChip = tbPlayerWinChip, zhuangSettle = zhuangSettle})
end

--取桌子状态
function Machine:getTableStatus(playerid)
	local seatPlayers = self:getSeatPlayers()
	for k, v in pairs(seatPlayers) do
		v.playing = nil
	end
	local zhuangPlayer = {}
	zhuangPlayer.seatid = self.zhuangSeatid
	zhuangPlayer.chip = self.zhuangLeftChip
	if self.isSysZhuang then
		zhuangPlayer.playerid = 0		
		zhuangPlayer.nick = self.sysZhuangNick
		zhuangPlayer.icon = self.sysZhuangHeadIcon		
	else		
		local player = self.player_list[self.zhuangPlayerId]
		zhuangPlayer.playerid = self.zhuangPlayerId
		zhuangPlayer.nick = player.nick		
		zhuangPlayer.icon = player.icon
	end
	table.insert(seatPlayers, zhuangPlayer)

	local myselfPlayer = {}
	myselfPlayer.playerid = playerid
	myselfPlayer.seatid = self.player_list[playerid].seatid 
	myselfPlayer.nick = self.player_list[playerid].nick 
	myselfPlayer.chip = self.player_list[playerid].chip
	myselfPlayer.icon = self.player_list[playerid].icon 

	local curRound = self.curRound
	if curRound == 0 then
		curRound = 1
	end

	local status = {		
		tableid = self.tableid,
		seat_player = seatPlayers,
		config = self:getConfig(),
		bet_pool_list = self:getPoolList(playerid),
		cur_round = curRound,
		win_list = self.winList,		
		cards = self.curCards,
		time = self:getOperTime(), --当前操作所剩余时间
		noseat_num = self:getNoSeatPlayerNum(),
		state = self.tbTableStateValue[self:getState()],
		myself_info = myselfPlayer,
	}	

	log.debug("playerid:" ..playerid, "Table status################",status)	
	return status
end

--请求下注
function Machine:onPlayerBet(playerid, args)
	local player = self.player_list[playerid]
	--self.poolName
	local addChip = args.add_chip
	local poolid = args.poolid
	local reason = {
		code = 7,
		moneytype = 1,
		game = player.game,
		gameid = self.gameid,
		gametype = self.roomid,
	}
	if self:getAllBet()	 + addChip > self.zhuangLeftChip then
		return GetErrorTable(38) --超过庄家赔付金额
	end

	if playerid == self.zhuangPlayerId then
		return GetErrorTable(36)
	end
	if self.tbTableStateValue[self:getState()] ~= self.tbTableStateValue.start then
		return GetErrorTable(32)
	end

	if player.chip < self.canBetMinMonney and
	 	self:getBetByPlayerId(playerid) == 0 then --没下过注提示
		return GetErrorTable(51)
	end

	if addChip > player.chip then
		return GetErrorTable(43)
	end

	if addChip > self.chipList[#self.chipList] then
		local data = {err_no = -1, err_msg = "加注数量错误！"}
		return data
	end
	if not self.poolPlayerAllBet[poolid][playerid] then 
		self.poolPlayerAllBet[poolid][playerid] = 0
	end

	if not self.poolPlayerChipList[poolid][playerid] then 
		self.poolPlayerChipList[poolid][playerid] = {}
	end

	local money = self:callGate(player, 'change_money', -addChip, reason)
	if not money then
		log.debug("onPlayerBet-------->playerid:",playerid, "addChip:", addChip, "player.chip :", player.chip)
		return
	end
	table.insert(self.poolPlayerChipList[poolid][playerid], addChip)
	table.insert(self.poolChipList[poolid], addChip)
	self.poolPlayerAllBet[poolid][playerid] = self.poolPlayerAllBet[poolid][playerid] + addChip
	self.poolAllBet[poolid] = self.poolAllBet[poolid] + addChip
	

	player.chip = money	
	local data = {
			zfb_nt_other_bet = {
				tableid = self.tableid,				
				pool_chip_list = {{
					id = poolid,
					seatid = player.seatid,
					playerid = playerid,
					all_bet = self.poolAllBet[poolid],
					my_bet = self.poolPlayerAllBet[poolid][playerid],
					chip_list = self:getBetChipTypeNum(self.chipList, {addChip}),
					chip = player.chip,
				}}				
			}
		}	
    self:sendToAll(data)

	local data = {}
	return data
end

--重复上场下注
function Machine:onPlayerRebet(playerid, args)
	local player = self.player_list[playerid]

	if playerid == self.zhuangPlayerId then
		AssertEx(false, 'zfb_rebet_res', 36)
	end
	if self.tbTableStateValue[self:getState()] ~= self.tbTableStateValue.start then
		AssertEx(false, 'zfb_rebet_res', 32)
	end
	
	local preBet = 0
	print("--------------1--rebet")
	for poolid = 1, self.maxPoolid do
		if self.prePoolPlayerChipList[poolid] and self.prePoolPlayerChipList[poolid][playerid] then
			 for k, v in pairs(self.prePoolPlayerChipList[poolid][playerid]) do	
			 	preBet = preBet + v
			 end			
		end
	end
	print("--------------2--rebet", preBet)
	if preBet == 0 then
		AssertEx(false, 'zfb_rebet_res', 31)
	elseif player.chip < self.canBetMinMonney and
	 	self:getBetByPlayerId(playerid) == 0 then --没下过注提示,金币不足20000
		AssertEx(false, 'zfb_rebet_res', 51)	
	elseif self:getAllBet() + preBet > self.zhuangLeftChip then
		AssertEx(false, 'zfb_rebet_res', 38) --超过庄家赔付金额
	elseif preBet > player.chip then
		AssertEx(false, 'zfb_rebet_res', 43)
	end

	local reason = {
		code = 7,
		moneytype = 1,
		game = player.game,
		gameid = self.gameid,
		gametype = self.roomid,
	}
	local money = self:callGate(player, 'change_money', -preBet, reason)
	if not money then
		log.debug("onPlayerRebet-------->playerid:",playerid, "preBet:", preBet, "player.chip :", player.chip )
		return
	end
	player.chip = money	

	local poolChipList = {}
	for poolid = 1, #self.chipList do
		if self.prePoolPlayerChipList[poolid] and self.prePoolPlayerChipList[poolid][playerid] 
			and not table.empty(self.prePoolPlayerChipList[poolid][playerid]) then
			--print("+++++++++++++++++++++++++++++++++++++++++++++++++ -1 poolid", poolid, self.prePoolPlayerChipList)
		 	local poolChips = {}
		 	poolChips.id = poolid
		 	poolChips.seatid = player.seatid
		 	poolChips.playerid = playerid
		 	poolChips.chip_list = self:getBetChipTypeNum(self.chipList, self.prePoolPlayerChipList[poolid][playerid])
		 	local poolAddChip = 0
		 	for k, v in pairs(self.prePoolPlayerChipList[poolid][playerid]) do 		
		 		if not self.poolPlayerAllBet[poolid][playerid] then 
					self.poolPlayerAllBet[poolid][playerid] = 0
				end

				if not self.poolPlayerChipList[poolid][playerid] then 
					self.poolPlayerChipList[poolid][playerid] = {}
				end

				table.insert(self.poolPlayerChipList[poolid][playerid], v)
				table.insert(self.poolChipList[poolid], v)
				self.poolPlayerAllBet[poolid][playerid] = self.poolPlayerAllBet[poolid][playerid] + v
				self.poolAllBet[poolid] = self.poolAllBet[poolid] + v
		 	end
		 	poolChips.all_bet = self.poolAllBet[poolid]
			poolChips.my_bet = self.poolPlayerAllBet[poolid][playerid]

		 	poolChips.playerid = playerid
		 	table.insert(poolChipList, poolChips)
		end
	end 
	

	for k, v in ipairs(poolChipList) do
		v.chip = player.chip 
	end
	--print("+++++++++++++++++++++++++++++++++++++++++++++++++3 player.chip", player.chip)

	local data = {
			zfb_nt_other_bet = {
				tableid = self.tableid,				
				pool_chip_list = poolChipList,
			}
		}	
	print("_________________rebet res data:",data)
    self:sendToAll(data)

	local data = {}
	return data
end

--合并筹码，小的合成大的，减少个数
function Machine:mergePoolChip(poolChip)

	local function _mergeChip( tbchip )
		if not tbchip or not next(tbchip) then
			return {}
		end
		local tbRes = {}	
		local total = 0
		for k, v in pairs(tbchip) do
			total = total + v
		end
		--print("before total:", total)

		for k=#self.chipList, 1, -1 do
			local chip = self.chipList[k]
			while total >= chip do
				total = total - chip
				table.insert(tbRes, chip)
			end 		
		end
		return tbRes
	end

	if table.empty(poolChip) then
		return poolChip
	end
	local poolChipRes = {}
	for poolid = 1, self.maxPoolid do
		poolChipRes[poolid] = {}
		for playerid, tbBet in pairs(poolChip[poolid]) do
			--print("============>x1", tbBet)
			local x = _mergeChip(tbBet)
			--print("============>x2", x)
			poolChipRes[poolid][playerid] = _mergeChip(tbBet)

		end		
		
	end
	return poolChipRes
end

--@override
function Machine:sitDownCallback( playerid )
	local player = self:getPlayer(playerid)
	local seatPlayer = self:getSeatPlayer(player)
	seatPlayer.diamond = nil
	seatPlayer.viplevel = nil
	seatPlayer.level = nil
	seatPlayer.playing = nil
	local data = {zfb_nt_seat_change = {
		tableid = self.tableid,
		seat_player = seatPlayer,
		seat = true,
	}}	
	self:sendToAll(data)
	self:ntNoSeatPlayerNum()
end

--坐下
function Machine:sitDown(playerid, seatid)
	if self.player_list[playerid].chip < self.seatMinMoney then
		return nil, GetErrorTable(44)
	end
	if self.zhuangSeatid == seatid then
	    return nil, GetErrorTable(27)
	end
	if self.player_list[playerid].seatid and
		 self:getState() == "start"  then
		for poolid = 1, self.maxPoolid do	 
			local betChips = self.poolPlayerAllBet[poolid][playerid]
			if betChips and betChips > 0 then
				return nil, GetErrorTable(33) --已下注不能换座
			end
		end
	end	
	return self.super.sitDown(self, playerid, seatid)
end

--@override
function Machine:sitUpCallback( seatid, playerid )
	local seatPlayer = {}
	seatPlayer.seatid = seatid
	seatPlayer.playerid = playerid
	local data = {zfb_nt_seat_change = {
		tableid = self.tableid,
		seat_player = seatPlayer,
		seat = false,
	}}
	self:sendToAll(data)
	self:ntNoSeatPlayerNum()
end

function Machine:sitUp(playerid)
	local player = self.player_list[playerid]
	if (player.seatid == self.zhuangSeatid and self:getState() == "start") 
		or (self:getState() == "start" and self:getBetByPlayerId(playerid) > 0) then		
		AssertEx(false , 'standup_res' , 30) --'请稍后站起'
	end
	local res = self.super.sitUp(self, playerid, seatid)
	self:ntNoSeatPlayerNum()
	return res
end

--退出上庄队列
function Machine:onPlayerRemoveZhuangList(playerid)
	for i, v in ipairs(self.zhuangPalyerList) do
		if playerid == v then
			table.remove(self.zhuangPalyerList, i)
			local player = self.player_list[playerid]
			local reason = {
				code = 6,
				moneytype = 1,
				game = player.game,
				gameid = self.gameid,
				gametype = self.roomid,
			}
			local money = self:callGate(player, 'change_money', player.zhuangChipFreeze, reason)
			if money then
				player.chip = money
			end			
			player.zhuangChipFreeze = 0
			local seatPlayer = self:getSeatPlayer(player)			
			self:updateProperty(playerid, seatPlayer)
			break
		end
	end
	local res = {shangzhuang_list = self:getZhuangList()}
	return res
end

--是否在上在队列
function Machine:inShangZhuangList(playerid)
	for k,v in pairs(self.zhuangPalyerList) do
		if playerid == v then
			return true
		end
	end	
end

--上庄处理
function Machine:onPlayerShangzhuang(playerid, args)
	local player = self.player_list[playerid]
	if self.zhuangPlayerId == playerid then
		return
	end
	if not args.zhuang_chip_freeze then
		return GetErrorTable(13)
	end
	if self:inShangZhuangList(playerid) then
		return GetErrorTable(37)
	end
	if player.chip < self.seatZhuangMinMoney or args.zhuang_chip_freeze > player.chip then
		return GetErrorTable(12)
	end
	local reason = {
		code = 6,
		moneytype = 1,
		game = player.game,
		gameid = self.gameid,
		gametype = self.roomid,
	}
	local money = self:callGate(player, 'change_money', -args.zhuang_chip_freeze, reason)
	if money then
		player.chip = money
	end
	player.zhuangChipFreeze = args.zhuang_chip_freeze

	local insertIndex = #self.zhuangPalyerList + 1 --上庄金额高的排前面
	for k=#self.zhuangPalyerList, 1, -1 do
		local zhuangChipFreeze = self.player_list[self.zhuangPalyerList[k]].zhuangChipFreeze	
		if args.zhuang_chip_freeze > zhuangChipFreeze then
			insertIndex = k
		end
		if args.zhuang_chip_freeze <= zhuangChipFreeze then
			break
		end
	end
	table.insert(self.zhuangPalyerList, insertIndex, playerid)

	local data = table.copy(player)

	local seatPlayer = self:getSeatPlayer(player)
	self:updateProperty(playerid, seatPlayer)

	local res = {shangzhuang_list = self:getZhuangList()}
	return res
end

--下庄处理
function Machine:onPlayerXiazhuang(playerid)
	local player = self:getPlayer(self.zhuangPlayerId) 
	if self.zhuangLeftChip <= player.zhuangChipFreeze  then
		return GetErrorTable(34)
	end
	if self:getState() == "rest" then
		self.profitWantXiazhuang = true
		local str = string.format("%s 赢了%d金币，跑庄了！", player.nick, self.zhuangLeftChip - player.zhuangChipFreeze)
		local data = { nt_content_prompt = {
					   type = 1,
					   strContent = str }
					 }
		self:sendToAll(data)
	end	
end

--获取上庄队列
function Machine:getZhuangList(args)
	local tbZhuangPalyer = {}
	for i, v in ipairs(self.zhuangPalyerList) do
		local player = self.player_list[v]
		local tb = {}
		tb.chip = player.zhuangChipFreeze
		tb.icon = player.icon
		tb.nick = player.nick
		tb.playerid = player.playerid
		table.insert(tbZhuangPalyer, tb)
	end
	return tbZhuangPalyer
end

function Machine:getHistoryList(args)
	return {history_list = self.winLossHistoryList}
end

function Machine:getNoSeatPlayerList(args)
	local  tbNoSeat = {}
	for k, v in pairs(self.player_list) do
		if v.playerid ~= self.zhuangPlayerId and not v.seatid then
			local player = {}
			player.playerid = v.playerid
			player.nick = v.nick
			player.chip = v.chip
			player.icon = v.icon
			table.insert(tbNoSeat, player)
		end
	end
	return {no_seat_player_list = tbNoSeat}
end
-------------------------------------------------------------------------------
-- 推送消息
-------------------------------------------------------------------------------
function Machine:ntStart()
	local data = {zfb_nt_start={
 		tableid = self.tableid,	
 		cur_round = self.curRound,
 		time = self.stateTime.start, 		
	}}
	log.debug("__________zfb_start", data)
	self:sendToAll(data)
end

function Machine:ntRest()
	local data = {zfb_nt_rest={
 		tableid = self.tableid,	
 		time = self.stateTime.rest
	}}
	log.debug("_________zfb_ntRest", data)
	self:sendToAll(data)	
end

--盈利下庄提示
function Machine:ntXiazhuangPrompt()		
	if self.isSysZhuang or self.curRound == 0 then
		return
	end
	
	local player = self:getPlayer(self.zhuangPlayerId)
	if self.zhuangLeftChip > player.zhuangChipFreeze then
		local data = {zfb_nt_xiazhuang_prompt={
	 		time = self.stateTime.rest - 1,
	 		winChip = self.zhuangLeftChip - player.zhuangChipFreeze,
	 	}}
		self:sendMessage(self.zhuangPlayerId, data)
	end	
end

function Machine:ntNoSeatPlayerNum(playerid)
	local num = self:getNoSeatPlayerNum()
	local data = {zfb_nt_no_seat_player_num = {
					tableid = self.tableid,	
 					standPlayerNum = num}}
 	if playerid then
 		self:sendToOther(playerid, data)
 	else
 		self:sendToAll(data)
 	end	
end

-----------------------------------------------------------------------------------
----------------------------------
-- 数据操作
----------------------------------

--状态对应的数字
function Machine:getStateNum()
	local state = self:getState()
	for k, v in pairs(self.gameStateTransitionTable) do 
		if state == v[1] then 
			return k
		end
	end
	return 
end

--桌子相关配置
function Machine:getConfig()
	return {	
		max_round   = self.maxRound, 	--最大轮数
		time_rest = self.stateTime.rest,
		time_start = self.stateTime.start,
		time_card = self.stateTime.card,
		time_end = self.stateTime.settlement,
		chip_list = self.chipList,
		seat_min_money = self.seatMinMoney,
		zhuang_min_money = self.seatZhuangMinMoney,
	}
end

--取下注池数据
function Machine:getPoolList(playerid)
	local poolList = {}
	for i=1,self.maxPoolid do 
		local pool = {}
		pool.id = i
		pool.all_bet = self.poolAllBet[i]
		pool.my_bet = self.poolPlayerAllBet[i][playerid] or 0
		pool.chip_list = self:getBetChipTypeNum(self.chipList, self.poolChipList[i]) 
		table.insert(poolList, pool)
	end	
	return poolList
end

--取牌
function Machine:getCard(playerid,num)	
	return self.rule:getCard(num)
end

--加载库存数据
function Machine:loadStockConfig()
	local exist = skynet.call("redis_service", "lua", "exists", nil , "stock:zhongfabai")
	self.repertoryConfig = {bf_bairen_repertory=500000, repertory_reduce_per = 0.25} ---默认的参数
	if exist then
		local res = skynet.call("redis_service", "lua", "hmget", nil , "stock:zhongfabai", "bf_bairen_repertory", "repertory_reduce_per")
		if next(res) then
			self.repertoryConfig["bf_bairen_repertory"] = tonumber(res [1])
			self.repertoryConfig["repertory_reduce_per"] = tonumber(res [2])
		end
	else
		skynet.call("redis_service", "lua", "hmset", nil , "stock:zhongfabai", self.repertoryConfig)
	end
end

--根据库存获取牌
function Machine:getCardWithStock(cards)
	self.count = self.count + 1
	if self:getAllBet() == 0 then
		return cards 
	end
 	local function _isRobot(uid)
 		return uid < 5000000
 	end
 	for i=1, 3020 do 
 		print("----------------------------------->i", i)
	 	local zhongCard  = {cards[1], cards[2]}
		local faCard	 = {cards[3], cards[4]}
		local baiCard 	 = {cards[5], cards[6]}
		local zhuangCard = {cards[7], cards[8]}

	 	if _isRobot(self.zhuangPlayerId) then--系统做庄
	 		local zhuangWinChip = 0
	 		for k, v in pairs(self.player_list) do
	 			if not _isRobot(v.playerid) then 
					for poolid = 1, self.maxPoolid do	 
						local betChips = self.poolPlayerAllBet[poolid][v.playerid]
						if betChips and betChips > 0 then
							local resCompare
							if poolid == self.poolName.zhong then
								resCompare =self.rule:compareCard(zhuangCard, zhongCard) 
							elseif poolid == self.poolName.fa then
								resCompare =self.rule:compareCard(zhuangCard, faCard) 
							elseif poolid == self.poolName.bai then
								resCompare =self.rule:compareCard(zhuangCard, baiCard) 
							end

							if resCompare > 0 then  --庄家赢
								zhuangWinChip = zhuangWinChip + betChips
							else--玩家赢
								zhuangWinChip = zhuangWinChip - betChips
							end
						end
					end
				end
			end
			if zhuangWinChip == 0 then
				return cards
			elseif zhuangWinChip < 0 and
			 math.abs(zhuangWinChip) >= self.repertoryConfig["bf_bairen_repertory"] and 
			 os.time() - self.calGetCardTime < 1 then
				table.mix(cards) --打乱牌
			else
				local changeStockChip = 0
				if zhuangWinChip > 0 then
					changeStockChip = zhuangWinChip * (1 - self.repertoryConfig["repertory_reduce_per"])
				else
					changeStockChip = zhuangWinChip
				end
				print("------------------------1-->changeStockChip", self.repertoryConfig["bf_bairen_repertory"], changeStockChip)
				self.repertoryConfig["bf_bairen_repertory"] = self.repertoryConfig["bf_bairen_repertory"] + changeStockChip
				skynet.call("redis_service", "lua", "hmset", nil , "stock:zhongfabai", {bf_bairen_repertory = self.repertoryConfig["bf_bairen_repertory"]})
				return cards
			end
	 	else--玩家做庄
	 		local strategyChips = 0
	 		local zhuangWinChip = 0
	 		for k, v in pairs(self.player_list) do
				for poolid = 1, self.maxPoolid do	 
					local betChips = self.poolPlayerAllBet[poolid][v.playerid]
					if betChips and betChips > 0 then
						local resCompare
						if poolid == self.poolName.zhong then
							resCompare =self.rule:compareCard(zhuangCard, zhongCard) 
						elseif poolid == self.poolName.fa then
							resCompare =self.rule:compareCard(zhuangCard, faCard) 
						elseif poolid == self.poolName.bai then
							resCompare =self.rule:compareCard(zhuangCard, baiCard) 
						end				

						if _isRobot(v.playerid) then
							if resCompare < 0 then
								strategyChips = strategyChips + betChips
							else
								strategyChips = strategyChips - betChips
							end
						else
							if resCompare < 0 then
								strategyChips = strategyChips - betChips
							else
								strategyChips = strategyChips + betChips
							end						
						end

						if resCompare > 0 then  --庄家赢
							zhuangWinChip = zhuangWinChip + betChips
						else--玩家赢
							zhuangWinChip = zhuangWinChip - betChips
						end
					end
				end
			end
			if self.repertoryConfig["bf_bairen_repertory"] + strategyChips <= 0 and 
			 	os.time() - self.calGetCardTime < 1 then
				table.mix(cards)
			else
				local changeStockChip = 0
				if zhuangWinChip < 0 then--庄输
					changeStockChip = zhuangWinChip * (1 - self.repertoryConfig["repertory_reduce_per"]) * (1 - self.severFeeRate)
				else
					changeStockChip = zhuangWinChip
				end
				print("-------------------------2-->changeStockChip", self.repertoryConfig["bf_bairen_repertory"], changeStockChip)
				self.repertoryConfig["bf_bairen_repertory"] = self.repertoryConfig["bf_bairen_repertory"] + changeStockChip
				skynet.call("redis_service", "lua", "hmset", nil , "stock:zhongfabai", {bf_bairen_repertory = self.repertoryConfig["bf_bairen_repertory"]})
				return cards
			end			
	 	end
	 end
	 return cards
end 

function Machine:record(settlementData)
	local record = {}
	if self:getAllBet() == 0 then
		return
	end
	record.settlementData = settlementData
	record.cards = self.curCards
	record.curRound = self.curRound
	record.zhuangPlayerId = self.zhuangPlayerId
	record.zhuangLeftChip = self.zhuangLeftChip
	
	record.playerBet = {} 
	for k, v in pairs(self.player_list) do
		if v.playerid ~= self.zhuangPlayerId then
			local tbBet = {playerid = v.playerid}
			local hasBet = false
			for poolid=1, self.maxPoolid do
				local bet = self.poolPlayerAllBet[poolid][v.playerid] or 0
				tbBet[poolid] = bet
				if bet > 0 then
					hasBet = true
				end
			end		
			if hasBet then
				table.insert(record.playerBet, tbBet)
			end				
		end	
	end	

	record.playerBet = {} 
	for poolid=1, self.maxPoolid do
		for playerid, bet in pairs(self.poolPlayerAllBet[poolid]) do
			local tbBet 
			for j, u in pairs(record.playerBet) do
				if u.playerid == playerid then
					tbBet = u
				end
			end
			if not tbBet then
				tbBet = {playerid = playerid}
				table.insert(record.playerBet, tbBet)
			end
			tbBet[poolid] = bet			
		end
	end


	local tableName = 'qclandlord_tablelog'
	local time = os.time()
	local str = tableName .." (tid, trdid, svid, tlcnt, tllog, tltime, game, gametype)"
	local sql = string.format("insert into %s values(%d,%d,%d,%d,'%s',%d,%d,%d);",
		str, self.tableid, self.trdid, 9, table.size(self.player_list), json.encode(record), time, self.gameid, self.roomid)
	local res = skynet.call("mysql_log", "lua", "execute", sql)

	local tlid = res.insert_id
	for k, v in pairs(record.playerBet) do

		local wlfold = self:getBetByPlayerId(v.playerid)
		local player = self.player_list[v.playerid]
		local wlleft = player.chip
		local wlwin = settlementData.tbPlayerWinChip[v.playerid]
		local wlflag = 2 --平局
		if wlwin > 0 then wlflag = 1 else wlflag = 0 end
		

		local str1 = 'qclandlord_winlog' .. " (tlid, uid, pfid, usid, tid, room_id, svid, trdid, wlfold, wlleft, wlwin, wlflag, wltime, game, gameid, gametype)"
		local sql1 = string.format("insert into %s values(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d);", str1, tlid, v.playerid, player.pfid or 0, player.usid or 0,self.tableid, self.roomid, 9,
														self.trdid, wlfold, wlleft, wlwin, wlflag, time, player.game or 0,self.gameid, self.roomid)
		local res = skynet.call("mysql_log", "lua", "execute", sql1)
		print("-------------------------------->res sql1",res, sql1)
	end

	if self.zhuangPlayerId == self.sysZhuangPlayerId then
		local tableName = "robot_coin_log" .. os.date("%Y%m%d")
		local sqlInsert = string.format("insert into %s (uid, coin, code, time,  game, gameid, gametype) values (%d, %d, %d, %d, %d, %d, %d);",
									 tableName, self.sysZhuangPlayerId, settlementData.zhuangSettle.winChips, 2, os.time(), self.sysDefaultGame, self.gameid, self.roomid)
		local x = skynet.send("mysql_log", "lua", "execute", sqlInsert)
	end
end

----------------------------------------------------------------------------------------------
---------开始游戏
---------------------------------------------------------------------------------------------- 
function Machine:start()
	self.fsm:set("settlement")
	self.fsm:fire("to_rest")
end

return Machine